<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="t('routes.components.permissionModal.permissionSetting')"
      @register="register"
      :showCancelBtn="false"
      :showOkBtn="false"
      :destroyOnClose="true"
      :minHeight="600"
      :width="1000"
    >
      <!-- 底部区域(会替换掉默认的按钮) -->
      <template #footer>
        <a-button @click="handlePerDisplay">{{
          t('routes.modal.permissionModal.permissionShow')
        }}</a-button>
        <a-button @click="handlePerSave">{{
          t('routes.modal.permissionModal.permissionEffect')
        }}</a-button>
        <a-button @click="handlerSetTypePermission">{{
          t('routes.modal.permissionModal.permissionType')
        }}</a-button>
        <a-button color="error" @click="handleCancel">{{
          t('routes.modal.permissionModal.exit')
        }}</a-button>
      </template>
      <Row :gutter="24" style="height: 300px">
        <Col :span="12" style="display: flex; flex-direction: column">
          <!-- 目录区 -->
          <Row>
            <Col :span="24">
              <div style="height: 250px; overflow-y: scroll; overflow-x: hidden">
                <BasicTree
                  checkable
                  :treeData="treeData"
                  :toolbar="true"
                  :search="true"
                  :title="t('routes.components.permissionModal.directory')"
                  :replaceFields="{ children: 'childrenpart' }"
                  v-model:checkedKeys="direSelectData"
                  @select="SelectDirectory"
                />
              </div>
            </Col>
          </Row>
          <!-- 用户区 -->
          <Row style="flex: 1; margin-top: 10px">
            <Col :span="24">
              <userPermission
                ref="userPermissionRef"
                :DirectoryData="selectDirectoryData"
                @sendData="handleData"
              />
            </Col>
          </Row>
        </Col>
        <!-- 权限区 -->
        <Col :span="12">
          <permissionSetting ref="permissionSettingRef" :viewUserPerData="viewUserPermissionData" />
        </Col>
      </Row>
    </BasicModal>
    <!-- 设定类型权限 -->
    <permissionTypeModal @register="registerTypeModal" />
    <!-- 权限显示 -->
    <permissionShowModal @register="registerPermissionShowModal" />
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { Row, Col } from 'ant-design-vue';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import { BasicTree } from '/@/components/Tree/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  import userPermission from './userPermission.vue';
  import permissionSetting from './permissionSetting.vue';
  import permissionTypeModal from '/@/views/demo/documentManager/permissionTypeModal.vue';
  import permissionShowModal from './permissionShowModal.vue';

  import {
    GetSelectedsonPrd,
    UpdatePermissions,
    ReverseParsePermissions,
  } from '/@/api/demo/document';

  const { t } = useI18n();
  // 目录树数据
  const treeData = ref([]);
  // 选中的目录
  const direSelectData = ref<any>([]);
  // 用户组件ref
  const userPermissionRef = ref<any>(null);
  // 权限组件ref
  const permissionSettingRef = ref<any>(null);
  // 目录选择数据
  const selectDirectoryData = ref<any>(null);
  // 查看用户目录权限数据
  const viewUserPermissionData = ref<any>(null);

  const { createMessage } = useMessage();

  // 目录Select事件
  const SelectDirectory = async (selectedKeys: any) => {
    selectDirectoryData.value = selectedKeys;
    if (userPermissionRef.value.activeKey == 'user') {
      viewUserPermissionData.value = await ReverseParsePermissions(
        userPermissionRef.value.selectUserData,
        selectDirectoryData.value.toString(),
      );
    } else if (userPermissionRef.value.activeKey == 'depart') {
      viewUserPermissionData.value = await ReverseParsePermissions(
        userPermissionRef.value.selectDepartData,
        selectDirectoryData.value.toString(),
      );
    } else if (userPermissionRef.value.activeKey == 'role') {
      viewUserPermissionData.value = await ReverseParsePermissions(
        userPermissionRef.value.selectRoleData,
        selectDirectoryData.value.toString(),
      );
    }
  };

  // 退出
  const handleCancel = () => {
    direSelectData.value = [];
    closeModal();
  };

  // 权限显示
  const handlePerDisplay = () => {
    // 判断目录层级关联还是层级独立
    const direResult =
      direSelectData.value.hasOwnProperty('checked') && direSelectData.value.checked.length > 0
        ? direSelectData.value.checked
        : direSelectData.value;
    // 判断部门层级关联还是层级独立
    const departSelectResult =
      userPermissionRef.value.departSelectedData.hasOwnProperty('checked') &&
      userPermissionRef.value.departSelectedData.checked.length > 0
        ? userPermissionRef.value.departSelectedData.checked
        : userPermissionRef.value.departSelectedData;
    // 判断角色层级关联还是层级独立
    const roleSelectResult =
      userPermissionRef.value.roleSelectedData.hasOwnProperty('checked') &&
      userPermissionRef.value.roleSelectedData.checked.length > 0
        ? userPermissionRef.value.roleSelectedData.checked
        : userPermissionRef.value.roleSelectedData;
    // 如果选中目录为空，则提示请选择数据目录进行权限显示
    // 如果有选中目录，并且userPermissionRef.value.activeKey = 'user',判断是否选中用户，如果没有选中用户，则提示请选择需要设置权限的用户,否则调用权限显示方法
    // 如果有选中目录，并且userPermissionRef.value.activeKey = 'depart'，判断是否选中部门，如果没有选中部门，则提示请选择需要设置权限的用户,否则调用权限显示方法
    // 如果有选中目录，并且userPermissionRef.value.activeKey = 'role'，判断是否选中角色，如果没有选中角色，则提示请选择需要设置权限的角色,否则调用权限显示方法
    if (direResult.length === 0) {
      createMessage.warning(t('routes.modal.permissionModal.selectCatalog'));
    } else {
      const selectedDataMap = {
        user: {
          data: userPermissionRef.value.userSelectedData,
          message: t('routes.modal.permissionModal.selectUser'),
        },
        depart: {
          data: departSelectResult,
          message: t('routes.modal.permissionModal.selectDepartment'),
        },
        role: {
          data: roleSelectResult,
          message: t('routes.modal.permissionModal.selectRole'),
        },
      };

      const { data, message } = selectedDataMap[userPermissionRef.value.activeKey] || {};
      if (!data || data.length === 0) {
        createMessage.warning(message);
      } else {
        if (userPermissionRef.value.activeKey === 'user') {
          openPermissionShowModal(true, {
            userSelectData: userPermissionRef.value.userSelectedData,
            direSelectData: direResult,
            userType: userPermissionRef.value.activeKey,
            type: 'fromFolder',
          });
        } else if (userPermissionRef.value.activeKey === 'depart') {
          openPermissionShowModal(true, {
            userSelectData: departSelectResult,
            direSelectData: direResult,
            userType: userPermissionRef.value.activeKey,
            type: 'fromFolder',
          });
        } else if (userPermissionRef.value.activeKey === 'role') {
          openPermissionShowModal(true, {
            userSelectData: roleSelectResult,
            direSelectData: direResult,
            userType: userPermissionRef.value.activeKey,
            type: 'fromFolder',
          });
        }
      }
    }
  };

  // 权限生效
  const handlePerSave = async () => {
    // 判断目录层级关联还是层级独立
    const direResult =
      direSelectData.value.hasOwnProperty('checked') && direSelectData.value.checked.length > 0
        ? direSelectData.value.checked
        : direSelectData.value;
    // 判断部门层级关联还是层级独立
    const departSelectResult =
      userPermissionRef.value.departSelectedData.hasOwnProperty('checked') &&
      userPermissionRef.value.departSelectedData.checked.length > 0
        ? userPermissionRef.value.departSelectedData.checked
        : userPermissionRef.value.departSelectedData;
    // 判断角色层级关联还是层级独立
    const roleSelectResult =
      userPermissionRef.value.roleSelectedData.hasOwnProperty('checked') &&
      userPermissionRef.value.roleSelectedData.checked.length > 0
        ? userPermissionRef.value.roleSelectedData.checked
        : userPermissionRef.value.roleSelectedData;
    // 判断权限层级关联还是层级独立
    const perSelectResult =
      permissionSettingRef.value.permissionSelectData.hasOwnProperty('checked') &&
      permissionSettingRef.value.permissionSelectData.checked.length > 0
        ? permissionSettingRef.value.permissionSelectData.checked
        : permissionSettingRef.value.permissionSelectData;
    if (direResult.length === 0) {
      createMessage.warning(t('routes.modal.permissionModal.selectCatalog'));
    } else {
      const selectedDataMap = {
        user: {
          data: userPermissionRef.value.userSelectedData,
          message: t('routes.modal.permissionModal.selectUser'),
        },
        depart: {
          data: departSelectResult,
          message: t('routes.modal.permissionModal.selectDepartment'),
        },
        role: {
          data: roleSelectResult,
          message: t('routes.modal.permissionModal.selectRole'),
        },
      };

      const { data, message } = selectedDataMap[userPermissionRef.value.activeKey] || {};
      if (!data || data.length === 0) {
        createMessage.warning(message);
      } else {
        if (userPermissionRef.value.activeKey === 'user') {
          await UpdatePermissions(
            direResult,
            userPermissionRef.value.userSelectedData,
            perSelectResult,
          );
          createMessage.success(t('routes.modal.permissionModal.permissionEffect'));
        } else if (userPermissionRef.value.activeKey === 'depart') {
          await UpdatePermissions(direResult, departSelectResult, perSelectResult);
          createMessage.success(t('routes.modal.permissionModal.permissionEffect'));
        } else if (userPermissionRef.value.activeKey === 'role') {
          await UpdatePermissions(direResult, roleSelectResult, perSelectResult);
          createMessage.success(t('routes.modal.permissionModal.permissionEffect'));
        }
      }
    }
  };

  const handleData = (data) => {
    viewUserPermissionData.value = data;
  };

  // 设定类型权限
  const handlerSetTypePermission = () => {
    openTypeModal(true);
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    // 获取目录数据接口参数
    const getTreeDataParams = data.treeKey;
    // 获取目录数据
    GetSelectedsonPrd(getTreeDataParams).then((res) => {
      treeData.value = res;
    });
  });
  // 设定类型权限
  const [registerTypeModal, { openModal: openTypeModal }] = useModal();
  // 权限显示
  const [registerPermissionShowModal, { openModal: openPermissionShowModal }] = useModal();
</script>

<style lang="less" scoped></style>
